<template>
  <div>
    <a-spin :spinning="printState.spinning">
      <div class="print">
        <!-- 左侧 -->
        <div class="left">
          <div class="print_editor">
            <button @click="handleAdd" class="card-item">
              <dl>
                <dt>
                  <img src="../../assets/image/addPrint.png" alt="" />
                </dt>
                <dd><span>添加打印机</span></dd>
              </dl>
            </button>
            <button @click="handleDelete" class="card-item">
              <dl>
                <dt>
                  <img src="../../assets/image/deletePrint.png" alt="" />
                </dt>
                <dd>
                  <span :class="{ disabled: !currentPrint.id }">删除打印机</span>
                </dd>
              </dl>
            </button>
            <button @click="handleOpen" class="card-item">
              <dl>
                <dt><img src="../../assets/image/openPrint.png" alt="" /></dt>
                <dd><span :class="{ disabled: !currentPrint.id }">开启打印机</span></dd>
              </dl>
            </button>
            <button @click="handleClose" class="card-item">
              <dl>
                <dt><img src="../../assets/image/closePrint.png" alt="" /></dt>
                <dd><span :class="{ disabled: !currentPrint.id }">关闭打印机</span></dd>
              </dl>
            </button>
          </div>
          <div class="print_list">
            <a-spin :spinning="printState.leftLoading">
              <div class="refresh" @click="heandleRefresh">
                <img src="../../assets/image/refresh.png" alt="" />
              </div>
              <div class="list" v-if="printState.printList && printState.printList.length">
                <li v-for="item in printState.printList" :key="item.id">
                  <img src="../../assets/image/printIcon.png" alt="" title="点击生成二维码" @click="heandleLeft(item)" />
                  <div @click="heandleRight(item)" style="flex:1">
                    <div>
                      <span class="list_icon list_icon_orange"></span><span class="name" :title="item.printerName">{{
                        item.printerName
                      }}</span>
                    </div>
                    <div>
                      <span class="list_icon list_icon_green"></span><span class="name">{{ item.printerPosition
                      }}</span>
                    </div>
                    <div>
                      <span class="list_icon" :class="`list_icon_1`"></span><span class="name"
                        :class="{ red: item.isInternetPrint === 2 }">{{
                          item.isInternetPrint === 1 ? "正常" : "云打印服务器已关闭"
                        }}</span>
                    </div>
                  </div>
                </li>
              </div>
              <a-empty v-else description="暂无数据" :image="simpleImage" />
            </a-spin>
          </div>
        </div>
        <!-- 右侧 -->
        <div class="right">
          <div class="current_task">
            <div class="header">
              <div class="title"><span></span>当前打印任务</div>
              <div class="search">
                <!-- <a-input v-model:value="currentForm.keyDown" placeholder="请输入关键词搜素">
                  <template #suffix>
                    <SearchOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
</a-input>
<a-button @click="getCurrentList" type="primary">查询</a-button> -->
              </div>
            </div>
            <a-table :scroll="{ x: 0, y: 100 }" :dataSource="printState.current.dataSource"
              :loading="printState.current.loading" :pagination="printState.current.pagination"
              :columns="printState.columnCurrent" size="small">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'index'">
                  <span>{{ index + 1 }}</span>
                </template>
                <template v-if="column.key === 'taskId'">
                  <a-tooltip placement="topLeft">
                    <template #title>
                      <span>{{ record.taskId }}</span>
                    </template>
                    {{ record.taskId }}
                  </a-tooltip>
                </template>
                <template v-if="column.key === 'fileName'">
                  <a-tooltip placement="topLeft">
                    <template #title>
                      <span>{{ record.fileName }}</span>
                    </template>
                    {{ record.fileName }}
                  </a-tooltip>
                </template>
                <template v-if="column.key === 'statua'">
                  <span :style="{ color: record.statua == '1' ? 'red' : '' }">{{
                    record.statua
                    }}</span>
                </template>
                <template v-if="column.key === 'button'">
                  <a-space :size="0">
                    <a-button type="link" :disabled="!record.internetUrl" @click="onPreview(record)">预览</a-button>
                    <a-button type="link" :disabled="!record.internetUrl" @click="onDownload(record)">下载</a-button>
                    <a-button type="link" danger @click="cancelPrient(record)">取消打印</a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>
          <div class="history_task">
            <div class="header">
              <div class="title"><span></span>历史打印任务</div>
              <div class="search">
                <!-- <a-input v-model:historyForm="historyForm.keyDown" placeholder="请输入关键词搜素">
                  <template #suffix>
                    <SearchOutlined style="color: rgba(0, 0, 0, 0.25)" />
                  </template>
                </a-input> -->
                <a-button @click="getHistoryList" type="primary">查询</a-button>
              </div>
            </div>
            <a-table :scroll="{ x: 0, y: 100 }" :dataSource="printState.history.dataSource"
              :loading="printState.history.loading" :pagination="printState.history.pagination"
              :columns="printState.columnHistory" size="mini">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'index'">
                  <span>{{ index + 1 }}</span>
                </template>
                <template v-if="column.key === 'taskId'">
                  <a-tooltip placement="topLeft">
                    <template #title>
                      <span>{{ record.taskId }}</span>
                    </template>
                    {{ record.taskId }}
                  </a-tooltip>
                </template>
                <template v-if="column.key === 'statua'">
                  <span :style="{ color: record.statua == '1' ? 'red' : '' }">{{
                    record.statua
                    }}</span>
                </template>
              </template>
            </a-table>
          </div>
        </div>
      </div>
    </a-spin>
    <!-- 添加打印机 -->
    <Add :addVisible="printState.addVisible" @trigger-parent="triggerParent" />
    <!-- 预览 -->
    <a-modal v-model:open="openRef" width="100%"
      wrap-class-name="full-modal">
      <iframe
      src="http://xuanmengbo.oss-cn-beijing.aliyuncs.com/yundy/f45278ae-b333-49cc-8905-7e7276abf930.pdf?Expires=1753433569&OSSAccessKeyId=LTAI5tGRuJqfMAdqXPDH34or&Signature=umIME6r6ETREiev%2BV2vQulXdDWo%3D"
      width="100%"
      height="100%"
      style="border: none;"
    />
    <template #footer>
      <div class="custom-footer">
        <!-- 取消按钮 -->
        <a-button
          key="cancel"
          type="default"
          @click="openRef = false"
        >
          取消
        </a-button>
      </div>
    </template>
    </a-modal>
    <!-- 扫码打印 -->
    <a-modal v-model:open="smRef" :footer="null">
      <img :src="smImgUrl" alt="">
    </a-modal>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue'
import Add from "./add.vue";
import { randomRange } from '@renderer/utils/index'
// 引入模块
import { message, Modal, Empty } from 'ant-design-vue'
import { columnCurrent, columnHistory } from "./column";
import QRCode from 'qrcode'
import api from '@renderer/api/print'
const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
let timer = ref(null)
const userInfo = ref(null)
const currentPrint = ref({})
const openRef = ref(false)
const smRef = ref(false)
const smImgUrl = ref('')
const printState = reactive({
  spinning: false,
  leftLoading: false,
  columnCurrent,
  columnHistory,
  addVisible: false,
  form: {
    printStationId: ''
  },
  printList: [],
  current: {
    form: {
      pageNum: 1,
      pageSize: 10,
      printStationId: '',
      printerFid: ''
    },
    loading: false,
    dataSource: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      defaultPageSize: 10,
      showQuickJumper: false,
      showSizeChanger: false,
      showTotal: (total) => {
        return `共 ${total} 条数据`;
      },
      pageSizeOptions: ["10", "15", "20"],
      onChange: (current) => {
        printState.current.pagination.current = current
        printState.current.form.pageNum = current
        getCurrentList()
      },
      onShowSizeChange: (pageNum, pageSize) => {
        printState.current.pagination.pageSize = pageSize
        printState.current.form.pageSize = pageSize
        getCurrentList()
      }
    }
  },
  history: {
    form: {
      pageNum: 1,
      pageSize: 10,
      printStationId: '',
      printerFid: ''
    },
    dataSource: [],
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      defaultPageSize: 10,
      showQuickJumper: false,
      showSizeChanger: false,
      showTotal: (total) => {
        return `共 ${total} 条数据`;
      },
      pageSizeOptions: ["10", "15", "20"],
      onChange: (current) => {
        printState.history.pagination.current = current
        printState.history.form.pageNum = current
        getHistoryList()
      },
      onShowSizeChange: (pageIndex, pageSize) => {
        printState.history.pagination.pageSize = pageSize
        printState.history.form.pageSize = pageSize
        getHistoryList()
      }
    }
  },
  currentSource: [],
  historySource: [],
  loginForm: {
    pinCode: ''
  }
})
const getList = async () => {
  printState.leftLoading = true
  window.api
    .fetchData(
      api.getPrinterList({ printStationId: userInfo.value.printStationId })

    )
    .then((res) => {
      if (res.code === 200) {
        printState.printList = res.data
      } else {
        message.error(res.data)
      }
    }
    ).finally(() => {
      setTimeout(() => {
        printState.leftLoading = false
      }, 1000)
    })
}
// 生成二维码
const heandleLeft = (item) => {
  console.log(item)
  // 生成为 Data URL（图片）
  let text = JSON.stringify({
    type: 'pint',
    fid: item.fid
  });
  console.log(text);

  QRCode.toDataURL(
    text,             // 二维码内容
    {
      width: 200,                       // 宽度（像素）
      height: 200,                      // 高度（像素）
      color: { dark: '#000', light: '#fff' } // 可选：颜色配置
    },
    (err, url) => {
      console.log('url',url);
      smRef.value = true
      smImgUrl.value = url
      // document.getElementById('qrcode').src = url; // 设置到 <img> 标签
    }
  );
}
const heandleRight = (item) => {
  clearInterval(timer.value)
  currentPrint.value = item
  seach()
  // timer.value = setInterval(seach, 5000)
}
const seach = () => {
  getCurrentList()
  getHistoryList()
}


// 获取当前打印任务
const getCurrentList = () => {
  printState.current.loading = true
  window.api
    .fetchData(
      api.currentTask(JSON.parse(JSON.stringify({ ...printState.current.form, printStationId: currentPrint.value.printStationId, printerFid: currentPrint.value.printerFid })))
    ).then(res => {
      if (res.code === 200) {
        printState.current.dataSource = res.rows
        printState.current.pagination.total = res.total
      }
    }).finally(() => {
      setTimeout(() => {
        printState.current.loading = false
      }, 1000)
    })
}
// 获取历史打印任务
const getHistoryList = () => {
  printState.history.loading = true
  window.api
    .fetchData(
      api.historyTask(JSON.parse(JSON.stringify({ ...printState.current.form, printStationId: currentPrint.value.printStationId, printerFid: currentPrint.value.printerFid })))
    ).then(res => {
      if (res.code === 200) {
        printState.history.dataSource = res.rows
        printState.history.pagination.total = res.total
      }
    }).finally(() => {
      setTimeout(() => {
        printState.history.loading = false
      }, 1000)
    })
}
const heandleRefresh = () => {
  getList()
}
// 添加打印机
const handleAdd = () => {
  printState.addVisible = true
}
const handleDelete = () => {
  if (!currentPrint.value.id) return
  Modal.confirm({
    title: '确认删除选中打印机？',
    content: '',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      console.log('OK')
      window.api
        .fetchData(
          api.deletePrinter({ id: currentPrint.value.id })
        )
        .then((res) => {
          if (res.code === 200) {
            seach()
          } else {
            message.error(res.data)
          }
        }
        )
    },
    onCancel() {
    }
  })
}
// 取消打印任务
const cancelPrient = (row) => {
  window.api
        .fetchData(
          api.cancelPrint({ taskId:row.taskId })
        )
        .then((res) => {
          if (res.code === 200) {
            seach()
          } else {
            message.error(res.data)
          }
        }
        )
}
const handleOpen = () => {
  if (!currentPrint.value.id) return
  Modal.confirm({
    title: '确认开启打印机？',
    content: '',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      console.log('OK')
      window.api
        .fetchData(
          api.switchPrinter({ id: currentPrint.value.id, isInternetPrint: '1' })
        )
        .then((res) => {
          if (res.code === 200) {
            getList()
          } else {
            message.error(res.data)
          }
        }
        )
    },
    onCancel() {
    }
  })
}
const handleClose = () => {
  if (!currentPrint.value.id) return
  Modal.confirm({
    title: '确认关闭打印机？',
    content: '',
    okText: '确定',
    cancelText: '取消',
    onOk() {
      console.log('OK')
      window.api
        .fetchData(
          api.switchPrinter({ id: currentPrint.value.id, isInternetPrint: '2' })
        )
        .then((res) => {
          if (res.code === 200) {
            getList()
          } else {
            message.error(res.data)
          }
        }
        )
    },
    onCancel() {
    }
  })
}
// 预览
const onPreview = (e) => {
  openRef.value = true
}
// 下载
const onDownload = (row) => {
  window.api.downloadPdf(row.internetUrl, row.fileName)
}
// 监听下载状态
window.api.onDownloadStatus((data) => {
  if (data.success) {
    message.warning('文件已保存到指定路径');
  } else {
    message.error(data.message);
  }
});

const triggerParent = (key, row = false) => {
  switch (key) {
    case 'seach':
      getList()
      break;
    case 'set-visible':
      printState.addVisible = row
      break;
    default:
      break;
  }
}

onMounted(async () => {
  userInfo.value = await window.api.getStoreData('user-info')
  getList()
});
</script>

<style lang="scss" scope>
@use './index.scss' as vars;
</style>
